package com.snif.web.attach.core.utils;

import com.sun.net.httpserver.HttpExchange;
import lombok.SneakyThrows;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 从HttpExchange中解析POST表单参数的工具类
 */
public class FormParamUtils {

	/**
	 * 从HttpExchange获取POST表单参数（application/x-www-form-urlencoded）
	 * @param exchange HttpExchange对象
	 * @return 表单参数的键值对Map
	 * @throws IOException 输入流读取异常
	 */
	public static Map<String, String> getFormParams(HttpExchange exchange) throws IOException {
		// // 1. 验证Content-Type是否为表单类型
		// String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
		// if (contentType == null ||
		// !contentType.contains("application/x-www-form-urlencoded")) {
		// throw new IllegalArgumentException("不支持的Content-Type，期望:
		// application/x-www-form-urlencoded");
		// }

		// 2. 读取表单请求体内容
		String formBody = readRequestBody(exchange);

		// 3. 解析表单内容为键值对Map
		return parseFormBody(formBody);
	}

	// Java 8兼容的输入流读取方法
	public static String readInputStreamAsString(InputStream is) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = reader.readLine()) != null) {
			sb.append(line);
		}
		return sb.toString();
	}

	/**
	 * 读取POST请求体内容
	 */
	private static String readRequestBody(HttpExchange exchange) throws IOException {
		// 使用BufferedReader读取输入流（兼容Java 8）
		try (BufferedReader reader = new BufferedReader(
				new InputStreamReader(exchange.getRequestBody(), StandardCharsets.UTF_8))) {
			StringBuilder body = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				body.append(line);
			}
			return body.toString();
		}
	}

	/**
	 * 解析表单请求体（格式：key1=value1&key2=value2）
	 */
	@SneakyThrows
	public static Map<String, String> parseFormBody(String formBody) {
		if (formBody == null || formBody.trim().isEmpty()) {
			return new HashMap<>(); // 空表单返回空Map
		}
		Map<String, String> params = new HashMap<>();
		// 按&分割键值对
		String[] pairs = formBody.split("&");
		for (String pair : pairs) {
			// 按=分割键和值（最多分割1次，处理值中包含=的情况）
			String[] keyValue = pair.split("=", 2);
			if (keyValue.length >= 1) {
				// URL解码（处理空格、中文、特殊符号）
				String enc = StandardCharsets.UTF_8.name().toString();
				String key = URLDecoder.decode(keyValue[0], enc);
				String value = keyValue.length == 2 ? URLDecoder.decode(keyValue[1], enc) : "";
				params.put(key, value);
			}
		}
		return params;
	}

}
